package servlet;

import DAO.CategoryDao;
import DAO.SubCategoryDao;
import DAO.SubcategoryTelevisionDao;
import DAO.TelevisionDao;
import bean.Category;
import bean.SubCategory;
import bean.Television;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "CategoryServlet", urlPatterns = "/category/*")
public class CategoryServlet extends HttpServlet {
    private CategoryDao categoryDao = new CategoryDao();
    private SubCategoryDao subCategoryDao = new SubCategoryDao();
    private TelevisionDao televisionDao = new TelevisionDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            // 默认显示所有商品和分类
            listAll(request, response);
        } else {
            try {
                Method method = this.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response.sendRedirect("error.jsp");
            }
        }

        // 在doGet方法中添加显示编辑表单的处理
        if ("showEditForm".equals(action)) {
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            Category category = categoryDao.getCategoryById(categoryId);
            request.setAttribute("category", category);
            request.getRequestDispatcher("edit_category.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            listAll(request, response);
        } else {
            try {
                Method method = this.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response.sendRedirect(request.getContextPath() + "/error.jsp");
            }
        }

        // 在doPost方法中添加更新分类的处理
        if ("updateCategory".equals(action)) {
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            
            Category category = new Category();
            category.setId(categoryId);
            category.setName(name);
            category.setDescription(description);
            
            categoryDao.updateCategory(category);
            
            response.sendRedirect("category?action=list");
        }
    }

    // 默认显示所有内容的方法
    public void listAll(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取所有大分类
        List<Category> categories = categoryDao.getAllCategories();
        request.setAttribute("categories", categories);

        // 为每个大分类获取其对应的小分类
        Map<Integer, List<SubCategory>> categorySubcategories = new HashMap<>();
        for (Category category : categories) {
            List<SubCategory> subCategories = subCategoryDao.getSubCategoriesByCategoryId(category.getId());
            categorySubcategories.put(category.getId(), subCategories);
        }
        request.setAttribute("categorySubcategories", categorySubcategories);

        // 获取所有商品
        List<Television> televisions = televisionDao.getAllTelevisions();
        request.setAttribute("televisions", televisions);

        request.getRequestDispatcher("/categories.jsp").forward(request, response);
    }

    // 按分类显示商品
    public void listByCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String categoryId = request.getParameter("categoryId");

        // 获取所有大分类（导航要）
        List<Category> categories = categoryDao.getAllCategories();
        request.setAttribute("categories", categories);

        // 获取指定分类的小分类
        List<SubCategory> subCategories = subCategoryDao.getSubCategoriesByCategoryId(Integer.parseInt(categoryId));
        request.setAttribute("subCategories", subCategories);

        // 获取当前分类信息
        Category currentCategory = categoryDao.getCategoryById(Integer.parseInt(categoryId));
        request.setAttribute("currentCategory", currentCategory);

        // 获取该分类下的所有商品
        List<Television> televisions = televisionDao.getAllTelevisions(); // 这里可能需要修改为获分类的商品
        request.setAttribute("televisions", televisions);

        request.getRequestDispatcher("/categories.jsp").forward(request, response);
    }

    // 删除分类
    public void delete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        if (id != null && !id.isEmpty()) {
            categoryDao.deleteCategory(Integer.parseInt(id));
        }
        listAll(request, response);
    }

    // 编辑分类
    public void edit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        Category category = new Category();
        category.setId(Integer.parseInt(id));
        category.setName(name);
        category.setDescription(description);

        categoryDao.updateCategory(category);
        listAll(request, response);
    }


    // 假设有一个方法来获取电视的 ID 列表
    public List<Integer> getTelevisionIdsBySubCategoryId(int subCategoryId) {
        // 这需要实现获取电视 ID 的逻辑
        // 如通过 subCategory 对象的某个属性
        return new ArrayList<>();
    }

    public void listBySubCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String subCategoryId = request.getParameter("subCategoryId");
        if (subCategoryId != null && !subCategoryId.isEmpty()) {
            try {
                int id = Integer.parseInt(subCategoryId);
                // 获取与小分类相关的商品
                List<Television> televisions = televisionDao.getTelevisionsBySubCategoryId(id);
                // 获取小分类信息
                SubCategory subCategory = subCategoryDao.getSubCategoryById(id);
                
                request.setAttribute("televisions", televisions);
                request.setAttribute("currentSubCategory", subCategory);
                
                // 返回商品展示部分的HTML
                request.getRequestDispatcher("/partials/televisionList.jsp").forward(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    public void deleteSubCategory(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String subCategoryId = request.getParameter("subCategoryId");
        if (subCategoryId != null && !subCategoryId.isEmpty()) {
            try {
                int id = Integer.parseInt(subCategoryId);
                // 先删除关联表中的数据
                new SubcategoryTelevisionDao().deleteRelationBySubCategoryId(id);
                // 然后删除小分类
                subCategoryDao.deleteSubCategory(id);
                // 重新加载页面数据
                listAll(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    public void addSubCategory(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 获取表单数据
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            
            // 验证输入
            if (name == null || name.trim().isEmpty()) {
                request.setAttribute("error", "分类名称不能为空");
                // 重新获取所有分类以便回显
                List<Category> categories = categoryDao.getAllCategories();
                request.setAttribute("categories", categories);
                request.setAttribute("selectedCategoryId", categoryId);
                request.getRequestDispatcher("/add_category.jsp").forward(request, response);
                return;
            }
            
            // 创建并保存新的小分类
            SubCategory subCategory = new SubCategory();
            subCategory.setCategoryId(categoryId);
            subCategory.setName(name.trim());
            subCategory.setDescription(description);
            
            // 保存到数据库
            int result = subCategoryDao.addSubCategory(subCategory);
            
            if (result > 0) {
                // 保存成功后重定向到分类列表页面
                response.sendRedirect(request.getContextPath() + "/category");
            } else {
                throw new Exception("保存失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            // 发生错误时，保持用户输入的数据
            List<Category> categories = categoryDao.getAllCategories();
            request.setAttribute("categories", categories);
            request.setAttribute("selectedCategoryId", 
                request.getParameter("categoryId") != null ? 
                Integer.parseInt(request.getParameter("categoryId")) : null);
            request.setAttribute("name", request.getParameter("name"));
            request.setAttribute("description", request.getParameter("description"));
            request.setAttribute("error", "添加分类失败：" + e.getMessage());
            request.getRequestDispatcher("/add_category.jsp").forward(request, response);
        }
    }

    public void showAddForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 获取所有大分类
            List<Category> categories = categoryDao.getAllCategories();
            request.setAttribute("categories", categories);
            
            // 获取选中的categoryId
            String categoryId = request.getParameter("categoryId");
            if (categoryId != null) {
                request.setAttribute("selectedCategoryId", Integer.parseInt(categoryId));
            }
            
            request.getRequestDispatcher("/add_category.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
} 